package main.SQL;

import main.MainApp;
import main.SQL.objects.SQLDocument;
import main.Trees.*;

import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
import javax.swing.tree.TreeNode;
import java.sql.*;
import java.util.HashMap;

public class FillSQLSmetModel {

    private SmetNode root, node;
    private Connection connSQL;

    public FillSQLSmetModel () {

    }

    public SmetNode run (SmetNode root, SmetNode node) {

        this.root = root;
        this.root.setName("Сметы");
        this.root.setAllowChildren(true);

        this.node = node;
        this.node.setAllowChildren(true);
        this.node.isString = false;

        //region Формирование дерева документов для сметы
//        SQLDocument topDoc = new SQLDocument();
//        SQLDocument curDoc;
//        TreeNode[] nodes = node.getPath();
//
//        for (int i = 2; i < nodes.length; i++) {
//
//            SmetNode curNode = (SmetNode) nodes[i];
//            curDoc = new SQLDocument();
//            curDoc.setDocName(curNode.getName());
//            curDoc.setDocNumber(curNode.getCode());
//            curDoc.setIsImportFactage(node.isImportFactage ? 1 : 0);
//
//            if (i == nodes.length - 1) {
//                SQLDocument parentDoc = (SQLDocument) topDoc.getLastChild();
//                curDoc.setParentDocId(parentDoc.getEpsId());
//                parentDoc.add(curDoc);
//                curDoc.setSmetId(node.getId());
//            } else {
//                if (node.isImportFactage) {
//                    curDoc.setEpsId(curNode.getId());
//                    if (i == 2) {
//                        topDoc = curDoc;
//                    } else {
//                        SQLDocument parentDoc = (SQLDocument) topDoc.getLastChild();
//                        curDoc.setParentDocId(parentDoc.getEpsId());
//                        parentDoc.add(curDoc);
//                    }
//
//                } else {
//                    if (i == 2) {
//                        curDoc.setTitulId(curNode.getId());
//                        topDoc = curDoc;
//                    } else {
//                        curDoc.setObjectId(curNode.getId());
//                        SQLDocument parentDoc = (SQLDocument) topDoc.getLastChild();
//                        curDoc.setParentDocId(parentDoc.getEpsId());
//                        parentDoc.add(curDoc);
//                    }
//                }
//            }
//        }
//        node.setDocument(topDoc);
//
        //endregion

        try {
            if (node.isImportFactage) {
                this.connSQL = MsSQLConnect.ConnectDB ("ImportFactage");
                fillImportFactageSmet();
            } else {
                this.connSQL = MsSQLConnect.ConnectDB ("TST");
                fillDocArchiveSmetTree();
            }
            connSQL.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return root;
    }

    //region Загрузка смет из ImportFactage
    private void fillImportFactageSmet() throws SQLException {

        Statement stmt = connSQL.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM Smr WHERE smet_id = " + node.getId() + " ORDER BY num ");

        while (rs.next()) {
            SmetNode newSmet = new SmetNode(rs.getString("num"), rs.getInt("id"), rs.getString("name"), rs.getString("unit"), rs.getDouble("volume"), rs.getDouble("mr"), rs.getDouble("t"), rs.getDouble("mech"), true, 0, node.getName());
            newSmet.setIsImportFactage(true);
            node.add(newSmet);
        }

        rs.close();
        stmt.close();

        node.isHeader = true;
        root.add(node);
    }
    //endregion

    //region Загружаем сметы DocArchive
    private void fillDocArchiveSmetTree() throws SQLException {

        Statement stmt = connSQL.createStatement();

        //region Загружаем разделы сметы
        HashMap<Integer, SmetNode> sectorMap = new HashMap<>();
        ResultSet rs = stmt.executeQuery("SELECT sect_id, sectLevel, sectNumber, sectName FROM  ks_Sm_section WHERE smet_id = " + node.getId());

        while (rs.next()) {
            SmetNode sector = new SmetNode(rs.getString(4), rs.getInt(1), rs.getString(3), true);
            sector.isHeader = false;
            sectorMap.put(sector.getId(), sector);
            node.add(sector);
        }
        //endregion

        //region Загружаем сметные строки
        rs = stmt.executeQuery("SELECT smr_id, smrNumber, smrName, smrUnit, smrQuantity, smrTotalDirectCost, smrTotalLabourCost, smrTotalLabourMashCost, sect_id\n" +
                "\tFROM  ks_Sm_rows\n" +
                "\tWHERE sect_id IN ( SELECT sect_id FROM ks_Sm_section WHERE smet_id = " + node.getId()+ ") order by smrNumber");

        while (rs.next()) {
            SmetNode smr = new SmetNode(rs.getString(2), rs.getInt(1), rs.getString(3), rs.getString(4), rs.getDouble(5), rs.getDouble(6), rs.getDouble(7), rs.getDouble(8), true, rs.getInt(9), node.getName());
            MainApp.allSmrMap.put("0-" + rs.getInt(1), smr);
            sectorMap.get(smr.getParentId()).add(smr);
        }
        //endregion

        root.add(node);
        node.isHeader = true;

        rs.close();
        stmt.close();
    }
    //endregion

}
